//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace OpenLS.Spreadsheet.Collections
{
    class HashSet<T> : IEnumerable<T>
    {
        readonly Dictionary<T, T> _table = new Dictionary<T, T>();
        public HashSet()
        {

        }

        public void Clear()
        {
            this._table.Clear();
        }

        public int Count
        {
            get { return _table.Count; }
        }

        public T GetItem (T t)
        {
            return this[t];
        }

        public T this[T t]
        {
            get
            {
                Contract.Ensures(Contains(Contract.Result<T>()));
                Contract.Ensures(Contains(t));
                if (!Contains(t))
                {
                    Add(t);
                    return t;
                }
                return _table[t];
            }
        }

        public HashSet(IEnumerable<T> items)
        {
            foreach (T item in items)
                if (!Contains(item))
                    Add(item);
        }
        public bool Contains (T t)
        {
            return _table.ContainsKey(t);
        }
        public void Add(T item)
        {
            Contract.Assert(!Contains(item));
            _table.Add(item, item);
        }
        public bool TryAdd(T t)
        {
            if (!Contains(t))
            {
                Add(t);
                return true;
            }
            return false;
        }

        #region IEnumerable<T> Members

        public new IEnumerator<T> GetEnumerator()
        {
            foreach (T t in _table.Keys)
                yield return t;
        }

        #endregion

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

}

